package com.test.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
 *  session监听器
 * @author YYR
 *
 */
public class SessionListener implements HttpSessionListener {


	@Override
	public void sessionCreated(HttpSessionEvent se) {
		System.out.println("=======开始产生session======");
		ServletContext ctx = se.getSession().getServletContext();
		Integer numSessions = (Integer) ctx.getAttribute("numSessions");
		if (numSessions == null) {
			numSessions = new Integer(1);

		} else {
			int count = numSessions.intValue();
			numSessions = new Integer(count + 1);
		}
		System.out.println("在线人数："+numSessions);
		ctx.setAttribute("numSessions", numSessions);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		System.out.println("=======开始销毁session======");
		ServletContext ctx = se.getSession().getServletContext();
		Integer numSessions = (Integer) ctx.getAttribute("numSessions");
		if (numSessions == null) {
			numSessions = new Integer(0);
		} else {
			int count = numSessions.intValue();
			numSessions = new Integer(count - 1);
		}
		System.out.println("在线人数"+numSessions);
		ctx.setAttribute("numSessions", numSessions);
	}
}
